package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private SetMealMapper setMealMapper;

    @Autowired
    private DishMapper dishMapper;

    @Override
    public List<ShoppingCart> listUserShoppingCart() {
        //从BaseContext中获取用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        return shoppingCartMapper.listUserShoppingCart(shoppingCart);
    }


    @Override
    public void cleanUserShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        log.info("clean shopping cart,user: {}", userId);
        shoppingCartMapper.cleanUserShoppingCart(userId);
    }


    @Override
    public void addUserShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setUserId(userId);

        //如果shopping_cart表存在一样的商品，修改number
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.listUserShoppingCart(shoppingCart);
        if(shoppingCarts!=null && shoppingCarts.size()>0){
            //实际上只会存在一条数据
            shoppingCart = shoppingCarts.get(0);
            //number+1
            shoppingCartMapper.updateNumberById(shoppingCart.getNumber()+1,shoppingCart.getId());

        }else{
            //如果不存在一样的商品，插入数据
            //可能是套餐
            if(shoppingCart.getSetmealId()!=null){
                Setmeal setmeal=setMealMapper.getById(shoppingCart.getSetmealId());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setAmount(setmeal.getPrice());
                shoppingCart.setImage(setmeal.getImage());
            }else{ //可能是普通菜品
                Dish dish = dishMapper.getById(shoppingCart.getDishId());
                shoppingCart.setName(dish.getName());
                shoppingCart.setAmount(dish.getPrice());
                shoppingCart.setImage(dish.getImage());
            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartMapper.insert(shoppingCart);
        }

    }
}
